<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Examples</title>
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link href="" rel="stylesheet">
    <script src="js/jquery-1.9.0.min.js"></script>
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=cc72db5d6f8295a36c30486830468a93"></script>
    <script src="js/xydata.js"></script>
    <style>
    #container {
        width: 100%;
        height: 360px;
    }
    </style>
</head>

<body>
    <div id="container"></div>
    <div>
        <input type="text" id="xy">
        <input type="text" id="readdress">
        <button id="exit_edit" disabled="disabled">退出编辑</button>
        <button id="edit_map">编辑模式</button>
        <button id="edit_add_f" disabled="disabled">添加标记</button>
        <button id="edit_del_f" disabled="disabled">删除标记</button>
        <button id="edit_mov_f" disabled="disabled">移动标记</button>
        <button id="edit_md" disabled="disabled">进入MD编辑</button>
    </div>
    <script>
    /**
     * 构建地图
     * @type {AMap}
     */

    var mapObj = new AMap.Map('container', {
        zoom: 5, //缩放级别
        center: [113.544184, 22.214936], //中心点
        isHotspot: true, //地图热点
        keyboardEnable: true, //键盘控制
        mapStyle: 'fresh' //normal（默认样式）、dark（深色样式）、light（浅色样式）、fresh(osm样式)
    });
    /**
     * 工具条&比例尺
     * @param  {AMap}   ) {                           var toolBar [description]
     * @return {[type]}   [description]
     */
    AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function() {
        //TODO  创建控件并添加
        var toolBar = new AMap.ToolBar();
        var scale = new AMap.Scale();
        mapObj.addControl(toolBar);
        mapObj.addControl(scale);
    });

    /**
     * 需将具体坐标传回后台
     * 初始化地图标记事件
     * @param {[type]} lng [description]
     * @param {[type]} lat [description]
     */
    var _ADD_LOCK_ = false;
    var lng, lat;
    var mapClick = AMap.event.addListener(mapObj, 'click', function(ev) {
        if (_ADD_LOCK_) {
            alw_click('edit_add_f');
        }

        console.log('ok')
        lng = ev.lnglat.getLng();
        lat = ev.lnglat.getLat();
        var lnglat = lng + ',' + lat;
        document.getElementById('xy').value = lnglat;

        reAddressCode(lnglat);
    });
    /**
     * 锁定工具栏
     */
    var edit_del_f = document.querySelector('#edit_del_f')
    var edit_mov_f = document.getElementById('edit_mov_f')
    var edit_add_f = document.getElementById('edit_add_f')
    var markers = [];
    var listers = [];

    document.getElementById('exit_edit').onclick = function() {
        edit_del_f.onclick = null;
        _ADD_LOCK_ = false;
        edit_mov_f.onclick = null;
        dis_click('edit_md');
        dis_click('edit_del_f');
        dis_click('edit_mov_f');
        dis_click('edit_add_f');
        dis_click('exit_edit');
        dis_f_lister();
    }
    document.getElementById('edit_map').onclick = function() {
        alw_click('exit_edit');
        add_f_lister();
    };

    function add_f_lister() {
        /**
         * 添加标记的锁
         * @type {Boolean}
         */
        _ADD_LOCK_ = true;
        /**
         * 对标记添加事件
         */
        for (var i = 0; i < markers.length; i++) {
            var lister = AMap.event.addListener(markers[i], 'click', function(ev) {
                /**
                 * 解锁工具栏
                 */
                re_t_lock();
                /**
                 * 监听工具栏
                 * @return {[type]} [description]
                 */
                var this_marker = this;

                edit_del_f.onclick = function() {
                    del_f(this_marker, t_lock);
                };
                edit_mov_f.onclick = function() {
                    mov_f(this_marker, t_lock);
                };
                edit_md.onclick = function() {
                    enter_md(this_marker, t_lock);
                };
            });
            listers.push(lister);
        }
        edit_add_f.onclick = function() {
            console.log(lng + lat)
            add_f(lng, lat, function() {
                dis_click('edit_add_f');
            });
        };
    }

    function dis_f_lister() {
        for (var i = 0; i < listers.length; i++) {
            AMap.event.removeListener(listers[i]);
        }
    }


    /**
     * 锁定工具栏
     * @return {[type]} [description]
     */
    function t_lock() {
        dis_click('edit_md');
        dis_click('edit_del_f');
        dis_click('edit_mov_f');
    }
    /**
     * 解锁
     * @return {[type]} [description]
     */
    function re_t_lock() {
        alw_click('edit_md');
        alw_click('edit_del_f');
        alw_click('edit_mov_f');
    }

    function dis_click(id) {
        document.getElementById(id).setAttribute('disabled', 'disabled');
    }

    function alw_click(id) {
        document.getElementById(id).removeAttribute('disabled');
    }


    function add_f(lng, lat, callback) {
        var marker = new AMap.Marker({
            position: [lng, lat],
            map: mapObj
        });
        markers.push(marker);
        /**
         * 为新增加的标记添加事件
         */
        var lister = AMap.event.addListener(markers[markers.length - 1], 'click', function(ev) {
            /**
             * 解锁工具栏
             */
            re_t_lock();
            /**
             * 监听工具栏
             * @return {[type]} [description]
             */
            var this_marker = this;

            edit_del_f.onclick = function() {
                del_f(this_marker, t_lock);
            };
            edit_mov_f.onclick = function() {
                mov_f(this_marker, t_lock);
            };
        });
        listers.push(lister);
        callback();
    }
    /**
     * 删除标记
     * @param  {[type]}   marker   [description]
     * @param  {Function} callback [description]
     * @return {[type]}            [description]
     */
    function del_f(marker, callback) {
        mapObj.remove(marker);
        callback();
    }
    /**
     * 移动标记
     * @param  {[type]}   this_marker [description]
     * @param  {Function} callback    [description]
     * @return {[type]}               [description]
     */
    function mov_f(this_marker, callback) {
        this_marker.setDraggable(true);
        callback();
    }
    /**
     * 进入md编辑
     * @param  {[type]} this_marker [description]
     * @param  {[type]} t_lock      [description]
     * @return {[type]}             [description]
     */
    function enter_md(this_marker, t_lock) {

    }
    /**
     * http://restapi.amap.com/v3/geocode/regeo?output=xml&location=116.310003,39.991957&key=<用户的key>&radius=1000&extensions=all
     * http逆地址编码服务
     */
    function reAddressCode(lnglat) {
        var key = "f04042dbf08df4d6b9dd84837d6aa8f4";
        var url = "http://restapi.amap.com/v3/geocode/regeo?output=json&location=" + lnglat + "&key=" + key + "&radius=1000&extensions=all";

        $.ajax({
            url: url,
            type: "GET",
            data: {},
            dataType: "json",
            success: function(data) {
                console.log(data)
                console.log(data.regeocode.formatted_address)
                var address = data.regeocode.formatted_address;
                if (address != "")
                    document.getElementById('readdress').value = address;
                else document.getElementById('readdress').value = "所查坐标超出能力范围";
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.status);
                console.log(XMLHttpRequest.readyState);
                console.log(textStatus);
            },
            complete: function(XMLHttpRequest, textStatus) {
                this; // 调用本次AJAX请求时传递的options参数
            }
        });
    }

    /**
     * 初始化标记
     * @type {AMap}
     */
    //province见Demo引用的JS文件
    for (var i = 0; i < provinces.length; i++) {
        /**
         * 根据设定的数据类型进行分发
         * @type {[type]}
         */
        var type = provinces[i].type;
        var icon = new AMap.Icon({
            image: 'http://vdata.amap.com/icons/b18/1/2.png',
            size: new AMap.Size(24, 24) //控制图标大小
        });
        switch (type) {
            case 0:
                marker = new AMap.Marker({
                    icon: icon, //content将会覆盖icon
                    position: provinces[i].center.split(','),
                    offset: new AMap.Pixel(-16, -16), //icon偏移量
                    zIndex: 101,
                    title: provinces[i].name,
                    topWhenMouseOver: true,
                    draggable: true,
                    raiseOnDrag: true, //拖拽效果
                    clickable: true,
                    map: mapObj
                });
                markers.push(marker);
                break;
            case 1:
                marker = new AMap.Marker({
                    position: provinces[i].center.split(','),
                    title: provinces[i].name,
                    map: mapObj
                });
                markers.push(marker);
                break;
            case 2:
                var content = "<div>宝岛台湾</div>";
                marker = new AMap.Marker({
                    content: content,
                    position: provinces[i].center.split(','),
                    title: provinces[i].name,
                    offset: new AMap.Pixel(0, 0),
                    map: mapObj
                });
                markers.push(marker);
                break;
        };
    };




    /**
     * 重设合适尺寸
     */
    // mapObj.setFitView();

    /**
     * 创建提示窗体
     * @type {AMap}
     */
    // var infowindow = new AMap.InfoWindow({
    //     content: '<p>ok</p>',
    //     offset: new AMap.Pixel(0, -30),
    //     size: new AMap.Size(230, 0)
    // });
    /**
     * 窗体点击监听
     * @param  {[type]} ) {                   infowindow.open(map, marker.getPosition())    } [description]
     * @return {[type]}   [description]
     */
    // var clickHandle = AMap.event.addListener(marker, 'click', function() {
    //     infowindow.open(map, marker.getPosition());
    // });
    </script>
</body>

</html>
